package com.haida.translation_web.trans.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haida.translation_web.trans.AbstractTranslator;
import com.haida.translation_web.util.Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.io.IOException;

public final class BaiduTranslator extends AbstractTranslator {
    private static final String url = "https://fanyi.baidu.com/v2transapi";

    public BaiduTranslator(){
        super(url);
    }

    @Override
    public void setLangSupport() {
        langMap.put("ZH", "zh");
        langMap.put("EN", "en");
        langMap.put("JP", "jp");
        langMap.put("KOR", "kor");
        langMap.put("FRA", "fra");
        langMap.put("RU", "ru");
        langMap.put("DE", "de");
    }

    @Override
    public void setFormData(String source, String text) {

    }

    @Override
    public void setFormData(String from, String to, String text) {
        formData.put("from", langMap.get(from));
        formData.put("to", langMap.get(to));
        formData.put("query", text);
        formData.put("transtype", "translang");
        formData.put("simple_means_flag", "3");
        formData.put("sign", token(text, "320305.131321201"));
        // formData.put("token", "7b35624ba7fe34e692ea909140d9582d");
        formData.put("token", "794afb0bac4f6b9e0954eda7785ca492");
    }

    @Override
    public String query() throws Exception {
        HttpPost request = new HttpPost(url);

        request.setEntity(new UrlEncodedFormEntity(Util.map2list(formData), "UTF-8"));
        request.setHeader("Cookie", "BIDUPSID=F14F295300969C152E39F568014A814D; PSTM=1621581013; BAIDUID=F14F295300969C1585F6FA0C3664349A:FG=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; __yjs_duid=1_2c569ea352896260b8ea3677213722c41621581021172; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BAIDUID_BFESS=F14F295300969C1585F6FA0C3664349A:FG=1; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1621658734,1621735509,1621863278,1622019882; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1622019882; __yjs_st=2_NGUwYmEzZWQ1NDBhYmEyYjNhMzZiMDdiNWYxZTBiZjk3OGE2NTc5ZDc1OGVmNzZiZDFhN2FkYTllNzNmZTRlZmRiY2MwNjY4YzZiMTFiZTY4ZTkzZTljMmUyMDZmYmQ5NDk1MjE3NzZkMzYwMjYxZWI1M2ZjN2U0NTc0YWQ1YzZiZDQ2ZWU3NDY3NmE1OWIwN2I2NjNiOTcxODhhOWExN2Y5ZjgyNWIxMDI0ZjExMThmOGZhNzk3OGQ3YjQyYjQ3NDAwMjFiNjY3ZGViZjY2YmIxNDA4NGYzYmJjNGM2OGQ5ZjcwNThhOGExNzAxZDk0YmNmZTUzNGE2ZDZkMzY0NF83X2YwN2RhNzNm; ab_sr=1.0.0_MjliNThmNThiZDczNTQ0ZGMyYzBiMGE4ZDk0ODA3NGM5NDhmNDhlMDhjNGRkMjQwMDBlNDA0MjYwNDU3ODY0YjlhODQzYzgxMDgyMGJlNmFlMTczYWEyOWNhZDExZmUx"); // fixme: 此处填写cookie
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36");

        CloseableHttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();

        String result = EntityUtils.toString(entity, "UTF-8");

        EntityUtils.consume(entity);
        response.getEntity().getContent().close();
        response.close();

        return result;
    }

    @Override
    public String parses(String text) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readTree(text).path("trans_result").findPath("dst").toString();
    }

    private String token(String text, String gtk) {
        String result = "";
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        try {
            // FileReader reader = new FileReader("./tk/Baidu.js");
            FileReader reader = new FileReader(this.getClass().getClassLoader().getResource("tk/Baidu.js").getPath());

            engine.eval(reader);
            if (engine instanceof Invocable) {
                Invocable invoke = (Invocable)engine;
                result = String.valueOf(invoke.invokeFunction("token", text, gtk));
            }
        // } catch (ScriptException | NoSuchMethodException | FileNotFoundException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
